package com.tuyan.aixiang.api.helper;

import android.content.Intent;
import android.os.Looper;

import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.activity.login.LoginActivity;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.util.Log;
import com.tuyan.aixiang.util.ToastUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * add common headers
 */
public class HeaderInterceptor implements Interceptor {

    private static final String TAG = "HeaderInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        String token = AppData.getToken();
        Request oldRequest = chain.request();
        Request.Builder builder = oldRequest
                .newBuilder()
                .addHeader("Content-Type", "application/json");
//                .addHeader("Accept", "application/json");

        if (null != token) {
            builder.addHeader(Constant.TOKEN_KEY, token);
        }
//                .addHeader("token", t);

        Request request = builder.build();

        Response response = chain.proceed(request);

        if (response.code() == 501 ) { // TODO token失效状态码
            AppData.clearAll();
            Log.d(TAG, ">>> response code =" + response.code());
            Looper.prepare();
            ToastUtil.makeShort("登录信息过期, 请重新登录");
            Intent intent = new Intent(MainApplication.getAppContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            MainApplication.getAppContext().startActivity(intent);
            Looper.loop();
        }


//        Log.d(TAG, "--> headers");
//        Log.d(TAG, "User-Device: " + AppData.getDevice().getSN());
//        Log.d(TAG, "--> Accept: application/json");
//        Log.d(TAG, "--> Access-Token: t");
        return response;
    }
}
